<template>
  <div class="chatPage">
    <ContentBox title="聊天" :fixed="true">
      <template slot="oleft"><van-icon color="#000000" name="arrow-left"/></template>
    </ContentBox>
    <notice :top="$remToPx('0.88')" class="not"></notice>
    <div class="chat_content" ref="scollBox">
      <div ref="longBox">
        <div v-for="(it, index) in message" :key="index">
          <div v-if="it.role === 'other'" class="other_item">
            <van-divider class="time">{{it.time}}</van-divider>
            <div class="msg_item">
              <van-image
                width=".8rem"
                height=".8rem"
                fit="cover"
                :radius="$remToPx(0.08)"
                :src="imUser.avatar"
              />
              <div class="msg_box">
                <span class="name">{{imUser.nickname}}</span>
                <div class="msg_detail" style="text-align: left">{{it.content}}</div>
              </div>
            </div>
          </div>
          <div v-if="it.role === 'mine'" class="mine_item">
            <van-divider class="time">{{it.time}}</van-divider>
            <div class="msg_item">
              <van-image
                width=".8rem"
                height=".8rem"
                fit="cover"
                :radius="$remToPx(0.08)"
                :src="it.avatar"
              />
              <div class="msg_box">
                <span class="name">{{it.nickname}}</span>
                <div class="msg_detail">{{it.content}}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="chat_footer">
      <!-- <van-icon name="photo" size=".44rem" color="666666"/> -->
      <input type="text" v-model="msgTest" placeholder="说点什么...">
      <div class="send" @click="send">发送</div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import moment from 'moment'
export default {
  data () {
    return {
      hasHis: false,
      message: [],
      msgTest: ''
    }
  },
  computed: {
    ...mapGetters([
      'uifo',
      'imUser',
      'imHis'
    ])
  },
  created () {
    console.log('imUser:', this.imUser)
    if (this.imUser && this.imUser.id) {
      // 用户存在
      this.$RC_clearUnreadCount(this.imUser.id).then(() => {
        this.getConversationList()
      })

      window.rongChat.subscribe((msg) => {
        this.RC_MessageListenerFn(msg)
      })

      const uIndex = this.getHisIndex({ id: this.imUser.id })
      console.log('--------------')
      console.log(uIndex)
      if (uIndex !== -1) {
        // eslint-disable-next-line no-undef
        this.$getRemoteHistoryMessages(RongIMLib.ConversationType.PRIVATE, this.imUser.id, (this.imHis[uIndex].unreadMessageCount + 2) * 1, this.imHis[uIndex].sentTime + 60000).then(data => {
          console.log('list', data.list)
          console.log('hasMsg', data.hasMsg)
          this.hasHis = data.hasMsg

          data.list.map(msg => {
            console.log(msg)
            this.messageHandle(msg).then(msgData => {
              console.log('----------------------------')
              console.log('监听到的包装的msg对象:', msgData)
              this.message.push(msgData)
            })
          })
        })
      }
    } else {
      this.$router.push('/')
    }
  },
  mounted () {
    console.log(this.$refs.scollBox.scrollTop)
    console.log(this.$refs.longBox.offsetHeight)
    this.$refs.scollBox.scrollTop = this.$refs.longBox.offsetHeight
  },
  methods: {
    send () {
      if (this.msgTest !== '') {
        const msgData = {
          role: 'mine',
          type: 'text',
          content: this.msgTest,
          nickname: this.uifo.nickname,
          id: this.uifo.id,
          avatar: this.uifo.avatar,
          time: moment().format('YYYY-MM-DD HH:mm:ss')
        }
        console.log('发送封装的信息', msgData)
        this.message.push(msgData)
        this.$RC_sendMessage(
          this.imUser.id,
          {
            content: this.msgTest,
            user: { name: this.$store.state.uifo.nickname, portrait: this.$store.state.uifo.avatar }
          }
        ).then(res => {
          console.log('发送成功:', res)
          this.msgTest = ''
          this.$refs.scollBox.scrollTop = this.$refs.longBox.offsetHeight
        })
      } else {
        this.msgTest = ''
        this.$toast('不能发送空内容')
      }
    },
    // 获取会话列表
    getConversationList () {
      this.$RC_getConversationList().then(res => {
        console.log('会话列表：', res)
        this.$store.commit('SET_IMHIS', res)
      })
    },
    // 消息监听处理回调函数
    RC_MessageListenerFn (message) {
      this.$RC_clearUnreadCount(this.imUser.id).then(() => {
        this.getConversationList()
      })
      console.log(message)
      this.messageHandle(message).then(msgData => {
        console.log('///////////////////////')
        console.log('监听到的包装的msg对象:', msgData)
        console.log(message.senderUserId === this.imUser.id)
        // if (message.senderUserId === this.imUser.id) {
        this.message.push(msgData)
        this.$refs.scollBox.scrollTop = this.$refs.longBox.offsetHeight
        // }
      })
    },
    // 获取历史记录用户索引
    getHisIndex (data) {
      const result = this.imHis.findIndex(his => {
        if (his.targetId === data.id) {
          return true
        }
        return false
      })
      return result
    },
    messageHandle (message) {
      return new Promise(resolve => {
        let msgData = null
        console.log('*******************')
        console.log(message)
        switch (message.messageType) {
          // eslint-disable-next-line no-undef
          case RongIMClient.MessageType.TextMessage:
            // message.content.content => 消息内容
            console.log(33333333333)
            msgData = {
              role: this.uifo.id === message.senderUserId ? 'mine' : 'other',
              type: 'text',
              content: message.content.content,
              nickname: message.content.user && message.content.user.name,
              id: message.senderUserId,
              avatar: message.content.user.portrait,
              time: moment(message.sentTime).format('YYYY-MM-DD HH:mm:ss')
            }
            break
          // eslint-disable-next-line no-undef
          case RongIMClient.MessageType.ImageMessage:
            // message.content.content => 图片缩略图 base64。
            // message.content.imageUri => 原图 URL。
            msgData = {
              role: this.uifo.id === message.senderUserId ? 'mine' : 'other',
              type: 'image',
              content: message.content.imageUri,
              nickname: message.content.user.name,
              id: message.senderUserId,
              avatar: message.content.user.portrait,
              time: moment(message.sentTime).format('YYYY-MM-DD HH:mm:ss')
            }
            break
          // eslint-disable-next-line no-undef
          case RongIMClient.MessageType.RichContentMessage:
            // message.content.content => 文本消息内容。
            // message.content.imageUri => 图片 base64。
            // message.content.url => 原图 URL。
            break
          default:
            // do something...
            break
        }
        console.log(msgData)
        resolve(msgData)
      })
    },
    // 查看更多历史纪录
    getMoreHis () {
      const t = moment(this.message[0].time, 'YYYY-MM-DD HH:mm:ss').valueOf()
      // eslint-disable-next-line no-undef
      this.$getRemoteHistoryMessages(RongIMLib.ConversationType.PRIVATE, this.imUser.id, 7, t).then(data => {
        console.log('list', data.list)
        console.log('hasMsg', data.hasMsg)
        this.hasHis = data.hasMsg
        data.list.map(msg => {
          this.messageHandle(msg).then(msgData => {
            console.log('**------')
            console.log('监听到的包装的msg对象:', msgData)
            this.message.push(msgData)
          })
        })
      })
    }
  }
}
</script>

<style lang="scss">
.chatPage{
  height: 100%;
  background: #f0f0f0;
  padding-top: 1.36rem;
  display: flex;
  flex-direction: column;
  .not{
    position: fixed;
    top: .88rem;
    width: 100%;
    left: 0;
  }
  .chat_content{
    flex: 1;
    padding: 0 .16rem .24rem;
    overflow: auto;
    .other_item{
      .msg_item{
        display: flex;
        flex-direction: row;
      }
    }
    .mine_item{
      .msg_item{
        display: flex;
        flex-direction: row-reverse;
        .name{
          text-align: right;
        }
      }
    }
    .time{
      color: #333333;
      font-size: .2rem;
    }
    .msg_item{
      display: flex;
      align-items: flex-start;
      .msg_box{
        display: flex;
        flex-direction: column;
        margin: 0 .16rem;
        .name{
          color: #999999;
          font-size: .2rem;
          margin-bottom: .08rem;
        }
        .msg_detail{
          color: #333333;
          font-size: .2rem;
          width: 5.22rem;
          background: #ffffff;
          border-radius: .08rem;
          padding: .16rem;
          word-break: break-all;
          text-align: right;
        }
      }
    }
  }
  .chat_footer{
    flex: 0 1 auto;
    height: .96rem;
    display: flex;
    align-items: center;
    background: #f6f6f6;
    width: 100%;
    padding: 0 .2rem;
    .send{
      color: #666666;
      font-size: .32rem;
      flex: 0 1 auto;
    }
    input{
      height: .6rem;
      background: #ffffff;
      border-radius: .36rem;
      font-size: .28rem;
      color: #000000;
      padding-left: .2rem;
      flex: 1;
      margin: 0 .16rem;
    }
  }
}
</style>
